package com.example.aop;


import com.alibaba.fastjson.JSONObject;
import com.example.mapper.OperteMapper;
import com.example.pojo.OperteLog;
import com.example.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Arrays;

@Slf4j
@Component
@Aspect
public class LogAspect {

    @Autowired
    private HttpServletRequest request;
    @Autowired
    private OperteMapper operteMapper;
    /*
    * AOP记录日志
    **/
    @Around("@annotation(com.example.anno.Log)")
    public Object recordLog(ProceedingJoinPoint joinPoint) throws Throwable {
        // 操作人id --当前登录人id
        //获取请求头中JWT令牌,解析令牌
        String jwt = request.getHeader("token");
        Claims claims = JwtUtils.ParseJwt(jwt);
        Integer operteUser = (Integer) claims.get("id");


        //操作时间
        LocalDateTime operteTime = LocalDateTime.now();

        //操作类名
        String className = joinPoint.getTarget().getClass().getName();

        //操作的方法名
        String methodName = joinPoint.getSignature().getName();

        //操作方法参数
        Object[] args = joinPoint.getArgs();
        String methodParam = Arrays.toString(args);

        //开始时间
        long begin = System.currentTimeMillis();
        //调用原始方法运行
        Object result = joinPoint.proceed();
        //结束时间
        long end = System.currentTimeMillis();

        //方法返回值
        String returnValue = JSONObject.toJSONString(result);

        //操作耗时
        Long costTime = end - begin;

        //记录操作日志
        OperteLog opertelog = new OperteLog(null,operteUser,operteTime,className,methodName,methodParam,returnValue,costTime);
        operteMapper.insert(opertelog);
        log.info("AOP记录操作日志 {}" ,opertelog);
        return result;
    }
}
